package com.dayatang.product.domain;

import java.util.List;

import javax.persistence.Cacheable;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * 文件名:RoleAssignment.java
 * 描述:角色,用户分配关联表
 * 创建时间:2012-6-7 下午5:24:56
 * 创建者:mluo
 * 版本号:v2.0
 */
@Entity
@Table(name = "role_assignments", 
	uniqueConstraints = @UniqueConstraint(columnNames = {"user_id", "role_id", "org_id"}))
@Cacheable
@NamedQueries({
	@NamedQuery(name = "findByUser", query = "select r from RoleAssignment r where r.user = ?")
})
public class RoleAssignment extends MyAbstractEntity {

	private static final long serialVersionUID = 6628380964547864312L;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "user_id", nullable = false)
	private PersonUser user;

	@NotNull
	@ManyToOne
	@JoinColumn(name = "role_id", nullable = false)
	private Role role;

	@ManyToOne
	@JoinColumn(name = "org_id")
	private Organization organization;
	
	public PersonUser getUser() {
		return user;
	}

	public void setUser(PersonUser user) {
		this.user = user;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	public int hashCode() {
		return new HashCodeBuilder().append(user).append(role).append(organization).toHashCode();
	}

	public boolean equals(Object other) {
		if (this == other) {
			return true;
		}
		if (!(other instanceof RoleAssignment)) {
			return false;
		}
		RoleAssignment that = (RoleAssignment) other;
		return new EqualsBuilder().append(this.getUser(), that.getUser()).append(this.getRole(), that.getRole()).append(this.getOrganization(), that.getOrganization()).isEquals();
	}

	public String toString() {
		return new ToStringBuilder(this).append(user).append(role).append(organization).toString();
	}
	
	/**
	 * 查找分配给用户的角色
	 * @param personUser
	 * @return
	 */
	public static List<RoleAssignment> findByUser(PersonUser personUser) {
		return getRepository().findByNamedQuery("findByUser", new Object[]{personUser}, RoleAssignment.class);
	}
	
}


